package com.ruoyi.plus.api;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.api.ApiResult;
import com.ruoyi.common.core.api.BaseApi;
import com.ruoyi.common.core.api.version.ApiVersion;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.plus.api.appLogin.vo.UpdatePhonePo;
import com.ruoyi.plus.api.po.LogoffUserPo;
import com.ruoyi.plus.api.po.SysUserPo;
import com.ruoyi.plus.util.OnlineTokenService;
import com.ruoyi.plus.utils.sms.ISmsService;
import com.ruoyi.plus.utils.sms.domain.CheckCodeModel;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author likun
 */
@Slf4j
@Api(tags = "SysUserApi-用户信息")
@ApiVersion
@RestController
@RequestMapping("/app/api/plus/sysUserApi")
public class SysUserApi extends BaseApi {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private OnlineTokenService onlineTokenService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISmsService smsService;


    @ApiOperation("changeUserInfo-修改用户信息")
    @PostMapping("/changeUserInfo")
    @Log(title = "changeUserInfo-修改用户信息", businessType = BusinessType.UPDATE)
    @ResponseBody
    public ApiResult<Boolean> changeUserInfo(@RequestBody @Valid SysUserPo po) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        if (StringUtils.isNotEmpty(po.getAvatar())) {
            sysUser.setAvatar(po.getAvatar());
        }
        if (StringUtils.isNotEmpty(po.getNickName())) {
            sysUser.setNickName(po.getNickName());
        }

        int i = sysUserService.updateUserProfile(sysUser);
        // 更新登录token中的用户信息
        onlineTokenService.updateLoginUserToken(Arrays.asList(sysUser));
        if (i > 0) {
            return new ApiResult<Boolean>(getApiVersion()).setData(true).setMsg("修改成功！");
        }

        // 返回信息
        return new ApiResult<Boolean>(getApiVersion()).setData(false).setMsg("修改失败！").setCode(-1);
    }

    @ApiOperation("logout-退出登录")
    @PostMapping("/logout")
    @Log(title = "logout-退出登录", businessType = BusinessType.UPDATE)
    @ResponseBody
    public ApiResult<Boolean> logout() throws Exception {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        onlineTokenService.forceLogoutByUserId(new Long[]{sysUser.getUserId()});
        return new ApiResult<Boolean>(getApiVersion()).setData(true).setMsg("退出登录成功！");
    }

    @ApiOperation("logoffUser-注销账号")
    @PostMapping("/logoffUser")
    @Log(title = "logoffUser-注销账号", businessType = BusinessType.DELETE)
    @ResponseBody
    public ApiResult<Boolean> logoffUser(@RequestBody @Valid LogoffUserPo po) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        if (!sysUser.getUserId().equals(po.getUserId())) {
            return new ApiResult<Boolean>(getApiVersion()).setData(false).setMsg("待注销账号与当前登录账号不一致！").setCode(-1);
        }

        if (StringUtils.isNotEmpty(po.getPassword())) {
            BCryptPasswordEncoder encode = new BCryptPasswordEncoder();
            if (!encode.matches(po.getPassword(), sysUser.getPassword())) {
                return new ApiResult<Boolean>(getApiVersion()).setData(false).setMsg("待注销账号密码输入错误！").setCode(-1);
            }
        }

        sysUserService.deleteUserById(sysUser.getUserId());
        // 返回信息
        return new ApiResult<Boolean>(getApiVersion()).setData(true).setMsg("用户注销成功！");
    }


    @ApiOperation("updatePhone-更新用户手机号")
    @Log(title = "updatePhone-更新用户手机号", businessType = BusinessType.UPDATE)
    @PostMapping("/updatePhone")
    @ResponseBody
    public ApiResult<Boolean> updatePhone(@RequestBody UpdatePhonePo po) throws IOException {
        CheckCodeModel checkCodeModel = smsService.checkCode(po.getPhone(), po.getCode());
        if (!checkCodeModel.isCheckResult()) {
            return new ApiResult<Boolean>().setCode(-1).setMsg(checkCodeModel.getCheckMsg()).setData(false);
        }

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        sysUser.setPhonenumber(po.getPhone());
        if (!sysUserService.checkPhoneUnique(sysUser)) {
            //校验用户是否被注册
            return new ApiResult<Boolean>(getApiVersion()).setData(false).setMsg("修改失败,手机号已被注册！").setCode(-1);
        }

        int i = sysUserService.updateUserProfile(sysUser);
        // 更新登录token中的用户信息
        onlineTokenService.updateLoginUserToken(Arrays.asList(sysUser));

        if (i > 0) {
            return new ApiResult<Boolean>(getApiVersion()).setData(true).setMsg("修改成功！");
        }

        // 返回信息
        return new ApiResult<Boolean>(getApiVersion()).setData(false).setMsg("修改失败！").setCode(-1);
    }


}
